'use strict';

module.exports = app => {
  return class extends app.Controller {
    * index(ctx) {
        const query=ctx.request.query;
        var pageParams='';
        if(query.pageParams){
            pageParams =JSON.parse(ctx.request.query.pageParams);
            if(!pageParams.order){
                pageParams.order=[['createdAt','DESC']];
            }
        }else {
            pageParams={
                pageNum:1,
                pageLimit:6,
                pageTotal:0,
                order:[['createdAt','DESC']],
                where:null
            }
        }
        let where=pageParams.where ? pageParams.where :null;
        var offset=(pageParams.pageNum - 1) * pageParams.pageLimit;
        var articles=yield ctx.model.Article.findAndCount({where:pageParams.where,limit:pageParams.pageLimit,offset:offset,order:pageParams.order});
        pageParams.pageTotal=Math.ceil(articles.count/pageParams.pageLimit);
        console.log('*******************');
        console.log(new Date());
        yield ctx.body={
            data:articles.rows,
            pageParams:pageParams
        };

    }
    * show(ctx){
        let id=ctx.params.id;
        let article=yield ctx.model.Article.findOne({where:{id:id},include:[{model:ctx.model.Nice,where:{userId:ctx.user.id},required: false}]});
        article.view++;
        article.save();
        let owenScore=yield ctx.model.Score.findOne({where:{userId:ctx.user.id,articleId:id}});
        let isHasScore=owenScore?true:false;
        let comment=yield ctx.model.query("select comment.*,user.`nickname` from `article_comments` as comment left join `users` as user on comment.`userId`=user.`id` where 1=1 and comment.`display`=1 and comment.`articleId`="+id, { type: ctx.model.QueryTypes.SELECT })
        let score={
            num:yield ctx.model.Score.count({where:{articleId:id}})
        };
        score.fraction=yield ctx.model.Score.sum('fraction',{where:{articleId:id}});
        score.fraction=parseFloat(score.fraction/score.num).toFixed(2);
        ctx.body={
            article:article,
            comment:comment,
            score:score,
            isHasScore:isHasScore
        };
    }
  };
};
